﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using PhotoGallery.Core.Business;
using PhotoGallery.Infrastructure.Helpers;
using System.Collections;
using PhotoGallery.Application.OnlineUserProvider;
using System.Web.Routing;
using PhotoGallery.Application;


namespace PhotoGallery.Modules.Account.Controllers
{
    public class AccountController : Controller
    {
        #region Field & Property


        #endregion
        #region Constructor
        public AccountController()
        {

            // tmp do nothing
        }

        #endregion



        #region 请求处理方法
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Index(AccountSearch packet)
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }

            AccountIndexModel model = Core.Business.Account.Search(packet);
            return View(model);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        /// 
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Add()
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }
            return View();
        }


        /// <summary>
        ///  创建
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        /// 
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Create(Core.Business.Account model)
        {
            if (model == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = "操作失败，系统发生了一个错误" };
                return RedirectToAction("Add");
            }
            CY.Security.SecurityHelper sh = new CY.Security.SecurityHelper();
            model.Password = sh.ComputeMD5Hash(model.Password);
            model.Save();
            TempData["HintMessage"] = new HintMessage { Content = string.Format("人员({0})添加成功", model.Name) };
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Edit(int? id)
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }

            Core.Business.Account model;

            if (id == null || !id.HasValue || (model = Core.Business.Account.Load(id.Value)) == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = "人员不存在，请确认人员是否存在", Type = HintMessageType.Error };
                return RedirectToAction("Index");
            }

            return View(model);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Update(Core.Business.Account model)
        {

            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }
            Core.Business.Account oringe = null;

            if (model == null || (oringe = Core.Business.Account.Load(model.Id)) == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = "人员不存在，请确认人员是否存在", Type = HintMessageType.Error };
                return RedirectToAction("Index");
            }

            oringe.Name = model.Name;
            oringe.Gender = model.Gender;
            oringe.Telephone = model.Telephone;
            oringe.Birthday = model.Birthday;
            oringe.Address = model.Address;

            oringe.Save();

            TempData["HintMessage"] = new HintMessage { Content = String.Format("人员({0})修改成功", model.Name) };

            return RedirectToAction("Index");
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Delete(int? id)
        {
            if (id == null || id.HasValue || id.Value > 0)
            {
                TempData["HintMessage"] = new HintMessage { Content = String.Format("请确认该人员是否存在！！"), Type = HintMessageType.Error };
            }

            Core.Business.Account account = Core.Business.Account.Load(id.Value);

            if (account == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = String.Format("请确认该人员是否存在！！"), Type = HintMessageType.Error };
            }
            else
            {
                account.DeleteOnSave();
                account.Save();
                TempData["HintMessage"] = new HintMessage { Content = String.Format("人员删除成功！！"), Type = HintMessageType.Error };

            }

            return RedirectToAction("Index");
        }


        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult EditPassword(int? id)
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult UpdatePassword(int? id, string loginName, string oldPwd, string newPwd)
        {
            if (!string.IsNullOrEmpty(loginName))
            {
                if (string.IsNullOrEmpty(newPwd))
                {
                    return Json(new { success = false, message = "当前输入的新密码不能为空" });
                }

                CY.Security.SecurityHelper sh = new CY.Security.SecurityHelper();

                oldPwd = sh.ComputeMD5Hash(oldPwd);

                Core.Business.Account account = Core.Business.Account.Load(UserSession.OnlineAccount.Id);

                if (account == null)
                    return Json(new { success = true, message = "请确认用户是否存在！", JsonRequestBehavior.AllowGet });

                if (account != null && account.LoginName.Equals(loginName) && account.Password.Equals(oldPwd))
                {
                    // 修改密码
                    newPwd = sh.ComputeMD5Hash(newPwd);
                    account.LoginName = loginName;
                    account.Password = newPwd;
                    account.LoginName = loginName;
                    return Json(new { success = true, message = "修改密码已成功", JsonRequestBehavior.AllowGet });
                }
                else
                {
                    return Json(new { success = false, message = "原密码错误" });
                }
            }
            else
            {
                return Json(new { success = false, message = "当前用户登录名不能为空" });
            }
        }

        #endregion

        #region Json

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        public JsonResult CheckLoginName(string LoginName)
        {

            if (string.IsNullOrEmpty(LoginName))
                return Json(new { success = false, message = "该名称已经被占用！", status = "error" });


            Core.Business.Account account = Core.Business.Account.FindByName(LoginName);

            if (account == null)
                return Json(new { success = true, message = "该名称可用！", status = "success" });
            else
                return Json(new { success = false, message = "该名称已经被占用！", status = "error" });

        }
        #endregion



        /// <summary>
        /// 在线统计
        /// </summary>

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute()]
        public JsonResult OnlineUsers()
        {
            ArrayList users = OnlineUserBlock.Components.oluMonitor.GetAllUsers();

            IList<int> ids = new List<int>();
            foreach (var u in users)
            {
                int id = default(int);
                if (!int.TryParse(((UserExtend)u).Username, out id) || id <= 0)
                    continue;
                ids.Add(id);
            }


            return Json(new { success = true, list = ids.Count }, JsonRequestBehavior.AllowGet);

        }


        #region Login & Logout
        /// <summary>
        /// 登录 不需要Session 过滤
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [OnlineUserLoginFilter()]
        public ActionResult Login(Core.Business.Account model)
        {
            if (string.IsNullOrEmpty(model.LoginName) || string.IsNullOrEmpty(model.Password))
            {
                TempData["HintMessage"] = new HintMessage { Content = "登录失败，请检查用户名和密码是否匹配" };
                return this.ReLogin("登录失败，请检查用户名和密码是否匹配！");
            }
            CY.Security.SecurityHelper sh = new CY.Security.SecurityHelper();

            string oldPwd = sh.ComputeMD5Hash(model.Password);
            Core.Business.Account account = Core.Business.Account.FindBy(model.LoginName.ToLower(), oldPwd.ToLower());
            if (account == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = "登录失败，请检查用户名和密码是否匹配" };
                return this.ReLogin("登录失败，请检查用户名和密码是否匹配！");
            }
            else
            {
                PhotoGallery.Application.UserSession.OnlineAccount = account;
                TempData["HintMessage"] = new HintMessage { Content = string.Format("登录成功，{0},欢迎您的到来！", account.Name) };
                return RedirectToAction("Index", "Home");
            }

        }


        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public ActionResult ReLogin(string reason)
        {
            if (string.IsNullOrEmpty(reason))
            {
                if (TempData["HintMessage"] != null)
                {
                    ViewData["HintMessage"] = TempData["HintMessage"];
                }
            }
            else
            {
                ViewData["HintMessage"] = new HintMessage { Content = !string.IsNullOrEmpty(reason) ? reason : "您已经退出！" };
            }

            return View("Login");
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>  

        [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
        [OnlineUserLogOutFilter(Order = 0)]
        public ActionResult LogOut()
        {
            PhotoGallery.Application.UserSession.Clean();

            var routeValueDictionary = new RouteValueDictionary
                                       {
                                           { "controller", "Account" }, // Security Controller
                                           { "action", "ReLogin" }, // Unauthorized Action
                                           { "reason", "您已经退出登录!" }  // Put the reason here
                                       };
            return new RedirectToRouteResult(routeValueDictionary);

        }



        #endregion


    }
}
